package com.demo.service.impl;


import java.lang.constant.Constable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.demo.config.AppConfig;
import com.demo.entity.constants.Constants;
import com.demo.entity.dto.SessionUserLoginDto;
import com.demo.entity.enums.MenuTypeEnum;
import com.demo.entity.enums.SysAccountStatusEnum;
import com.demo.entity.enums.UserStatusEnum;
import com.demo.entity.po.SysAccount;

import com.demo.entity.po.SysMenu;
import com.demo.entity.po.SysRole;
import com.demo.entity.query.SysAccountQuery;

import com.demo.entity.query.SysMenuQuery;
import com.demo.entity.query.SysRoleQuery;
import com.demo.entity.vo.PaginationResultVO;

import com.demo.entity.vo.SysMenuVO;
import com.demo.exception.BusinessException;
import com.demo.service.SysAccountService;

import com.demo.service.SysMenuService;
import com.demo.service.SysRoleService;
import com.demo.utils.CopyTools;
import com.demo.utils.StringTools;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.demo.entity.query.SimplePage;

import com.demo.mappers.SysAccountMapper;

import com.demo.entity.enums.PageSize;
import org.springframework.transaction.annotation.Transactional;


@Service("sysAccountService")
public class SysAccountServiceImpl implements SysAccountService{

	@Resource
	private SysAccountMapper<SysAccount,SysAccountQuery> sysAccountMapper;

	@Resource
	private AppConfig appConfig;

	@Resource
	private SysMenuService sysMenuService;

	@Resource
	private SysRoleService sysRoleService;




	/**
	 * 根据条件查询列表
	 */
	public List<SysAccount> findListByParam(SysAccountQuery query) { 
		return this.sysAccountMapper.selectList(query);
	}

	/**
	 * 根据条件查询数量
	 */
	public Integer findCountByParam(SysAccountQuery query){
		return this.sysAccountMapper.selectCount(query);
	}

	/**
	 * 分页查询
	 */
	public PaginationResultVO<SysAccount> findListByPage(SysAccountQuery  query) { 
		int count = this.findCountByParam(query);
		int pageSize = query.getPageSize()==null?PageSize.SIZE15.getSize():query.getPageSize();
		SimplePage page = new SimplePage(query.getPageNo(),count,pageSize);
		query.setSimplePage(page);
		List<SysAccount> list = this.findListByParam(query);
		return new PaginationResultVO(count,page.getPageSize(),page.getPageNo(),page.getPageTotal(),list);
	}

	/**
	 * 新增
	 */
	public Integer add(SysAccount bean) { 
		return this.sysAccountMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	public Integer addBatch(List<SysAccount> listBean) { 
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.sysAccountMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	public Integer addOrUpdateBatch(List<SysAccount> listBean) { 
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.sysAccountMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 根据UserId查询
	 */
	public SysAccount getSysAccountByUserId(Integer userId) {
		SysAccount sysAccount = this.sysAccountMapper.selectByUserId(userId);
		return sysAccount;
	}

	/**
	 * 根据UserId更新
	 */
	@Transactional(rollbackFor = Exception.class)
	public Integer updateSysAccountByUserId(SysAccount bean, Integer userId) {
		return sysAccountMapper.updateByUserId(bean,userId);
	}


	public void updateSysAccount(SysAccount bean, Integer userId) {
		SysAccount phoneDb = sysAccountMapper.selectByPhone(bean.getPhone());
		if (phoneDb != null && !phoneDb.getUserId().equals(bean.getUserId())) {
			throw new BusinessException("手机号已存在");
		}
		SysAccount emailDb = sysAccountMapper.selectByEmail(bean.getEmail());
		if (emailDb != null && !emailDb.getUserId().equals(bean.getUserId())) {
			throw new BusinessException("邮箱已经存在");
		}
		updateSysAccountByUserId(bean,userId);
	}



	/**
	 * 根据UserId删除
	 */
	public Integer deleteSysAccountByUserId(Integer userId) { 
		return this.sysAccountMapper.deleteByUserId(userId);
	}

	/**
	 * 根据Phone查询
	 */
	public SysAccount getSysAccountByPhone(String phone) { 
		return this.sysAccountMapper.selectByPhone(phone);
	}

	/**
	 * 根据Phone更新
	 */
	public Integer updateSysAccountByPhone(SysAccount bean, String phone) { 
		return this.sysAccountMapper.updateByPhone(bean,phone);
	}

	/**
	 * 根据Phone删除
	 */
	public Integer deleteSysAccountByPhone(String phone) { 
		return this.sysAccountMapper.deleteByPhone(phone);
	}

	@Override
	public SessionUserLoginDto login(String phone, String password) {
		// 登录判断
		SysAccount sysAccount = this.sysAccountMapper.selectByPhone(phone);
		if (sysAccount == null) {
			throw new BusinessException("账号或者密码错误");
		}

		if (SysAccountStatusEnum.DISABLE.getStatus().equals(sysAccount.getStatus())) {
			throw new BusinessException("账号已禁用");
		}
		if (!sysAccount.getPassword().equals(password)) {
			throw new BusinessException("账号或者密码错误");
		}

		SessionUserLoginDto adminDto = new SessionUserLoginDto();
		adminDto.setUserId(sysAccount.getUserId());
		adminDto.setUserName(sysAccount.getUserName());

		// 查询所有的菜单项
		List<SysMenu> allMenus;
		if (!StringTools.isEmpty(appConfig.getSuperAdminPhones()) &&
				ArrayUtils.contains(appConfig.getSuperAdminPhones().split(","), phone)) {
			adminDto.setSuperAdmin(true);

			SysMenuQuery query = new SysMenuQuery();
			query.setFormate2Tree(false);
			query.setOrderBy("sort asc");
			allMenus = sysMenuService.findListByParam(query);
		} else {
			adminDto.setSuperAdmin(false);
			allMenus = sysMenuService.getAllMenuByRoleIds(sysAccount.getRoles());
		}
		// 查询权限列表
		List<String> permissionCodeList = new ArrayList<>();

		List<SysMenu> menuList = new ArrayList<>();
		for (SysMenu sysMenu : allMenus) {
			if (MenuTypeEnum.MEMU.getType().equals(sysMenu.getMenuType())) {
				menuList.add(sysMenu);
			}
			permissionCodeList.add(sysMenu.getPermissionCode());
		}
		menuList = sysMenuService.convertLine2Tree4Menu(menuList, 0);
		if (menuList.isEmpty()) {
			throw new BusinessException("请联系管理员分配角色");
		}
		List<SysMenuVO> menuVOList = new ArrayList<>();
		menuList.forEach(item -> {
			SysMenuVO menuVO = CopyTools.copy(item, SysMenuVO.class);
			menuVO.setChildren(CopyTools.copyList(item.getChildren(), SysMenuVO.class));
			menuVOList.add(menuVO);
		});
		adminDto.setMenuList(menuVOList);
		adminDto.setPermissionCodeList(permissionCodeList);
		return adminDto;
	}

	@Override
	public void saveSysAccount(SysAccount sysAccount) {
		SysAccount phoneDb = sysAccountMapper.selectByPhone(sysAccount.getPhone());
		if (phoneDb != null && (sysAccount.getUserId() == null || !phoneDb.getUserId().equals(sysAccount.getUserId()))) {
			throw new BusinessException("手机号已存在");
		}
		if (sysAccount.getUserId() == null) {
			sysAccount.setCreateTime(new Date());
			sysAccount.setStatus(UserStatusEnum.ENABLE.getStatus());
			sysAccount.setPassword(StringTools.encodeByMD5(sysAccount.getPassword()));
			this.sysAccountMapper.insert(sysAccount);
		} else {
			sysAccount.setPassword(null);
			sysAccount.setStatus(null);
			this.sysAccountMapper.updateByUserId(sysAccount, sysAccount.getUserId());
		}
	}


	/**
	 * 注册账号
	 * @param phone
	 * @param password
	 */
	@Override
	public void register(String phone, String password) {
		SysAccount sysAccount = new SysAccount();
		sysAccount.setPhone(phone);
		sysAccount.setPassword(password);
		SysRole sysRole = sysRoleService.getSysRoleByRoleId(Integer.parseInt(appConfig.getRegisterRoleId()));
		if (sysRole==null){
			throw new BusinessException("系统未设置默认注册角色，请联系管理员");
		}
		sysAccount.setPosition(sysRole.getRoleName());
		sysAccount.setRoles(String.valueOf(appConfig.getRegisterRoleId()));
		saveSysAccount(sysAccount);
	}
}